﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private event EventHandler _testEventHandler;
        public Form1()
        {
            InitializeComponent();
            _testEventHandler += OnTestEvent;
            //Thread t = new Thread(() =>
            //{
            //    try
            //    {
            //        throw new Exception("多线程异常");
            //    }
            //    catch (Exception ex)
            //    {
            //        BeginInvoke((Action)(() => throw ex));
            //    }
            //});
            //t.Start();
        }

        private void OnTestEvent(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Thread t = new Thread(() =>
            //{
            //    var request = WebRequest.Create("https://www.github.com");
            //    var response = request.GetResponse();
            //    var stream = response.GetResponseStream();
            //    using (var reader = new StreamReader(stream))
            //    {
            //        var content = reader.ReadLine();
            //    }
            //});
            //t.Start();
            var request = HttpWebRequest.Create("https://www.github.com");
            request.BeginGetResponse(this.AsyncCallbackImpl, request);
            //_testEventHandler?.Invoke(this, new EventArgs());
            //Test(AsyncCallbackImpl2, this);
        }

        private void AsyncCallbackImpl(IAsyncResult ar)
        {
            var request = ar.AsyncState as WebRequest;
            var response = request?.EndGetResponse(ar);
            var stream = response?.GetResponseStream();
            using (var reader = new StreamReader(stream))
            {
                var content = reader.ReadLine();
            }
        }

        private void AsyncCallbackImpl2(IAsyncResult ar)
        {
            
          
        }

        private void Test(AsyncCallback callback, object state)
        {
            callback?.Invoke(new Task<int>(() =>
            {
                return 1;
            }));
        }
    }
}
